package com.wg.wuge.tulin.jvm;

import java.util.LinkedList;

public class WaitPoolTest {

    LinkedList<ConnectTest> pool = new LinkedList<>();

    public void putConnect() {
        synchronized (pool) {
            if (pool.size() < 20) {
                pool.add(new ConnectTest());
                pool.notifyAll();
            }
        }
    }

    public ConnectTest getConnect(long millis) throws InterruptedException {
        synchronized (pool) {
            if (millis <= 0) {
                while (pool.isEmpty()) {
                    pool.wait();
                }
                return pool.removeFirst();
            }
            Long endTime = System.currentTimeMillis() + millis;
            Long remaing = millis;
            while (pool.isEmpty() && remaing >= 0) {
                pool.wait(remaing);
                remaing = endTime - System.currentTimeMillis();
            }
            ConnectTest result = null;
            if (!pool.isEmpty()) {
                result = pool.removeFirst();
            }
            return result;
        }
    }

}
